package hardware;

import java.util.LinkedList;
import java.util.List;

public class InstructionBuffer {
	private final String NO_ENOUGH_PLACE = "no enough place";
	private final String NO_ENOUGH_INSTRUCTIONS = "no enough instructions in buffer";
	private LinkedList<Instruction> buffer;
	private int maxSize;

	public InstructionBuffer(int m) {
		maxSize = m;
		buffer = new LinkedList<Instruction>();
	}

	/**
	 * put number of instructions in the instruction buffer.
	 * 
	 * @param instructions
	 *            list of instructions i want to add.
	 * @throws Exception
	 *             throws exception if there is no enough place in the buffer.
	 */
	void putInBuffer(List<Instruction> instructions) throws Exception {
		if ((buffer.size() + instructions.size()) <= maxSize) {
			for (int i = 0; i < instructions.size(); i++) {
				buffer.add(instructions.get(i));
			}
		} else {
			throw new Exception(NO_ENOUGH_PLACE, new Throwable());
		}
	}

	/**
	 * Gets number of instructions from the buffer.
	 * 
	 * @param m
	 *            number of instructions i want to get.
	 * @return list of instructions i got from the buffer.
	 * @throws Exception
	 *             if there is no enough instructions in buffer.
	 */
	LinkedList<Instruction> getInstructions(int m) throws Exception {
		LinkedList<Instruction> instructions = new LinkedList<Instruction>();
		if (m > buffer.size()) {
			throw new Exception(NO_ENOUGH_INSTRUCTIONS, new Throwable());
		}
		for (int i = 0; i < m; i++) {
			instructions.add(buffer.remove());
		}
		return instructions;
	}
}
